import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 这个脚本主要用于执行部分基础sql，被Opengauss_Compatibility_A_To_Binary_Float_Case0027调用
 * @Owner ：lwx1133724
 * @Create At： 2024/10/24
 */
public class To_Binary_Float_Case0027 {
    public static void main(String[] args) {
        if (args.length < 4) {
            System.out.println("need para: host:ip,dbname,user,password");
            return;
        }

        try (Connection conn = DriverManager.getConnection(
                "jdbc:postgresql://" + args[0] + "/" + args[1], args[2], args[3])) {
            String[] sqlStatements = {
	    	"drop table if exists t_tbf_0027;\n",
            "create table t_tbf_0027(v1 float4, v2 varchar(100), v3 float8);\n",
            "insert into t_tbf_0027 values (null, null, null);\n",
            "insert into t_tbf_0027 values (666, 'test', 999);\n",
            "insert into t_tbf_0027 values (-3.402E+38, 'test', -3.402E+38);\n",
            "insert into t_tbf_0027 values (3.402E+38, 'test', 3.402E+38);\n",
            "insert into t_tbf_0027 values (-3.402E+38, 'test', -1.79E+308);\n",
            "insert into t_tbf_0027 values (-3.402E+38, 'test', 1.79E+308);\n",
            "select to_binary_float(v1 default 1 on conversion error), v2, to_binary_float(v3) from t_tbf_0027;\n"
            };

            for (String sql : sqlStatements) {

                if (sql.trim().toUpperCase().startsWith("SELECT")) {
                    executeSelectAndPrintResults(conn, sql);
                } else {

                    try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                        pstmt.execute();
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private static void executeSelectAndPrintResults(Connection conn, String sql) throws SQLException {
        try (PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet resultSet = pstmt.executeQuery()) {
            while (resultSet.next()) {
                int columnCount = resultSet.getMetaData().getColumnCount();
                for (int i = 1; i <= columnCount; i++) {
                    System.out.println(resultSet.getMetaData().getColumnName(i) + " = " + resultSet.getString(i));
                }
            }
        }
    }
}